﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using zichan.Entity;
using zichan.DAL;
using MvcPaging;
namespace zichan.BLL
{
    public class IPService
    {
        public static IP Get(int id)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                return db.IPs.Where(o => o.Id == id).FirstOrDefault();
            }
        }
        public static IPagedList<IP> List(string ip, int? machineRoomId, int? statu, int pageIndex, int pageSize)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                IQueryable<IP> w = db.IPs.Where(o => !o.isDelete.HasValue);
                List<int> IpIds = db.PutawayServers.Where(o => o.Statu == 1 && o.IPId.HasValue).Select(o => o.IPId.Value).ToArray().ToList();
                List<string> subIpIds =db.PutawayServers.Where(o => o.Statu == 1 && !string.IsNullOrEmpty(o.SubIPIds)).Select(o => o.SubIPIds).ToList();
                foreach(string s in subIpIds)
                {
                    List<int> slist = Array.ConvertAll<string, int>(s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), o => Convert.ToInt32(o)).ToList();
                    IpIds.AddRange(slist);
                }
                if (!string.IsNullOrEmpty(ip))
                    w = w.Where(o => o.Ip.Contains(ip));
                if (machineRoomId.HasValue)
                    w = w.Where(o => o.MachineRoomId == machineRoomId);
                if (statu.HasValue)
                {
                    if (statu.Value == 1)
                    {
                        w = w.Where(o => IpIds.Contains(o.Id));
                    }
                    if (statu.Value == 0)
                    {
                        w = w.Where(o => !IpIds.Contains(o.Id));
                    }
                }
                List<IP> list = w.OrderByDescending(o => o.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                List<int> ids = list.Select(o => o.MachineRoomId).Distinct().ToList();
                var idNames = db.MachineRooms.Where(o => ids.Contains(o.Id)).Select(o => new { o.Id, o.Name });
                foreach (IP i in list)
                {
                    i.MachineRoomName = idNames.FirstOrDefault(o => o.Id == i.MachineRoomId).Name;
                    if (IpIds.Contains(i.Id))
                    {
                        i.IsUsed = 1;
                    }
                }
                return list.OrderByDescending(o => o.Id).ToPagedList(pageIndex - 1, pageSize, w.Count());
            }
        }
        public static List<IP> List(string ip, int? machineRoomId, int? statu)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                IQueryable<IP> w = db.IPs.Where(o=>!o.isDelete.HasValue);
                List<int> IpIds = db.PutawayServers.Where(o => o.Statu == 1 && o.IPId.HasValue).Select(o => o.IPId.Value).ToArray().ToList();
                List<string> subIpIds = db.PutawayServers.Where(o => o.Statu == 1 && !string.IsNullOrEmpty(o.SubIPIds)).Select(o => o.SubIPIds).ToList();
                foreach (string s in subIpIds)
                {
                    List<int> slist = Array.ConvertAll<string, int>(s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), o => Convert.ToInt32(o)).ToList();
                    IpIds.AddRange(slist);
                }
                if (!string.IsNullOrEmpty(ip))
                    w = w.Where(o => o.Ip.Contains(ip));
                if (machineRoomId.HasValue)
                    w = w.Where(o => o.MachineRoomId == machineRoomId);
                if (statu.HasValue)
                {
                    if (statu.Value == 1)
                    {
                        w = w.Where(o => IpIds.Contains(o.Id));
                    }
                    if (statu.Value == 0)
                    {
                        w = w.Where(o => !IpIds.Contains(o.Id));
                    }
                }
                List<int> ids = w.Select(o => o.MachineRoomId).ToList();

                var idNames = db.MachineRooms.Where(o => ids.Contains(o.Id)).Select(o => new { o.Id, o.Name });
                foreach (IP i in w)
                {
                    i.MachineRoomName = idNames.FirstOrDefault(o => o.Id == i.MachineRoomId).Name;
                    i.statuName = "未使用";
                    if (IpIds.Contains(i.Id))
                    {
                        i.statuName = "已使用";
                    }
                }
                return w.OrderByDescending(o => o.Id).ToList();
            }
        }
        public static string Add(IP model)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                try
                {
                    if (db.IPs.Count(o =>!o.isDelete.HasValue&&o.Ip.Trim() == model.Ip.Trim()) > 0)
                        return "IP已存在";
                    db.IPs.Add(model);
                    db.SaveChanges();
                    return string.Empty;
                }
                catch (Exception ex)
                {
                    return "无法添加";
                }
            }
        }
        public static string AddBatch(List<string> ipList, out List<string> existIp, out List<string> ipListForLog, int classId)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                try
                {
                    existIp = new List<string>();
                    ipListForLog = new List<string>();
                    List<IP> List = new List<IP>();
                    foreach (string n in ipList)
                    {
                        if (db.IPs.Count(o =>!o.isDelete.HasValue&&o.Ip.Trim() == n.Trim()) > 0 || List.Count(o => o.Ip.Trim() == n.Trim()) > 0)
                        {
                            existIp.Add(n);
                            continue;
                        }
                        ipListForLog.Add(n);
                        IP model = new IP();
                        model.Ip = n;
                        model.MachineRoomId = classId;
                        List.Add(model);
                    }
                    if (List.Count() > 0)
                    {
                        db.IPs.AddRange(List);
                        db.SaveChanges();
                    }
                    return string.Empty;
                }
                catch (Exception ex)
                {
                    existIp = new List<string>();
                    ipListForLog = new List<string>();
                    return "无法添加，请重试";
                }
            }
        }
        public static string Edit(IP model)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                try
                {
                    if (db.IPs.Count(o =>!o.isDelete.HasValue&&o.Ip.Trim() == model.Ip.Trim()&&o.Id!=model.Id&&model.MachineRoomId==o.MachineRoomId) > 0)
                        return "IP已存在";
                    db.Entry(model).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    return string.Empty;
                }
                catch (Exception ex)
                {
                    return "无法编辑";
                }
            }
        }
        public static string Delete(int id)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {

                if (db.PutawayServers.Count(o =>( o.IPId == id||o.SubIPIds.Contains(id.ToString()))&&o.Statu==1) > 0)
                    return "该IP正在使用，无法删除";
                IP model = db.IPs.Where(o => o.Id == id).FirstOrDefault();
                model.isDelete = 1;
                db.SaveChanges();
                MachineRoomLogService.Add(2, "删除" + "\"" + model.Ip + "\"");
                return string.Empty;
            }
        }
        public static List<IP> List(int? id,int machineRoomId)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                List<string> ids = Array.ConvertAll<int, string>(db.PutawayServers.Where(o => o.Statu == 1 && o.IPId.HasValue).Select(o => o.IPId.Value).ToArray(), s => s.ToString()).ToList();
                if(id.HasValue)
                    ids = Array.ConvertAll<int, string>(db.PutawayServers.Where(o => o.Statu == 1 && o.IPId.HasValue&&o.Id!=id).Select(o => o.IPId.Value).ToArray(), s => s.ToString()).ToList();
                List<string> subIds = db.PutawayServers.Where(o => o.Statu == 1 && !string.IsNullOrEmpty(o.SubIPIds)).Select(o => o.SubIPIds).ToList();
                ids.AddRange(subIds);
                string ips = string.Join(",", ids);
                if (string.IsNullOrEmpty(ips))
                    return db.Database.SqlQuery<IP>("select * from IPs where isDelete IS NULL and MachineRoomId=" + machineRoomId).ToList();
                else
                    return db.Database.SqlQuery<IP>("select * from IPs where Id not in (" + ips + ") and isDelete IS NULL and MachineRoomId=" + machineRoomId).ToList();
            }
        }
        public static List<IP> NoUseList()
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                List<string> ids = Array.ConvertAll<int, string>(db.PutawayServers.Where(o => o.Statu == 1 && o.IPId.HasValue).Select(o => o.IPId.Value).ToArray(), s => s.ToString()).ToList();
                List<string> subIds = db.PutawayServers.Where(o => o.Statu == 1 && !string.IsNullOrEmpty(o.SubIPIds)).Select(o => o.SubIPIds).ToList();
                ids.AddRange(subIds);
                string ips = string.Join(",", ids);
                if (string.IsNullOrEmpty(ips))
                    return db.Database.SqlQuery<IP>("select * from IPs where isDelete IS NULL").ToList();
                else
                    return db.Database.SqlQuery<IP>("select * from IPs where Id not in (" + ips + ") and isDelete IS NULL").ToList();
            }
        }
        public static List<IP> NoUseList(int machineRoomId,int id)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                List<string> ids = Array.ConvertAll<int, string>(db.PutawayServers.Where(o => o.Statu == 1 && o.IPId.HasValue).Select(o => o.IPId.Value).ToArray(), s => s.ToString()).ToList();
                List<string> subIds = db.PutawayServers.Where(o => o.Statu == 1 && !string.IsNullOrEmpty(o.SubIPIds)).Select(o => o.SubIPIds).ToList();
                ids.AddRange(subIds);
                ids.Add(id.ToString());
                string ips = string.Join(",", ids);
                    return db.Database.SqlQuery<IP>("select * from IPs where Id not in (" + ips + ") and MachineRoomId="+machineRoomId+" and isDelete IS NULL").ToList();
            }
        }
        public static List<IP> IpForEditList(int machineRoomId,int id)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                List<string> ids = Array.ConvertAll<int, string>(db.PutawayServers.Where(o => o.Statu == 1 && o.Id != id && o.IPId.HasValue).Select(o => o.IPId.Value).ToArray(), s => s.ToString()).Distinct().ToList();
                List<string> subIds = db.PutawayServers.Where(o => o.Statu == 1 && !string.IsNullOrEmpty(o.SubIPIds)).Select(o => o.SubIPIds).Distinct().ToList();
                ids.AddRange(subIds);
                string ips = string.Join(",", ids);
                if (!string.IsNullOrEmpty(ips))
                {
                    if (machineRoomId != 0)
                        return db.Database.SqlQuery<IP>("select * from IPs where Id not in (" + ips + ") and MachineRoomId=" + machineRoomId + " and isDelete IS NULL").ToList();
                    else
                        return db.Database.SqlQuery<IP>("select * from IPs where Id not in (" + ips + ") and isDelete IS NULL").ToList();
                }
                else
                    return db.IPs.Where(o=>o.MachineRoomId==machineRoomId&&!o.isDelete.HasValue).ToList();
            }
        }
        public static List<IP> SubIpForEditList(int machineRoomId,int id)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                List<string> subIds = db.PutawayServers.Where(o => o.Statu == 1 && o.Id != id && !string.IsNullOrEmpty(o.SubIPIds)).Select(o => o.SubIPIds).Distinct().ToList();
                List<string> ids = Array.ConvertAll<int, string>(db.PutawayServers.Where(o => o.Statu == 1 && o.IPId.HasValue).Select(o => o.IPId.Value).ToArray(), s => s.ToString()).Distinct().ToList();
                ids.AddRange(subIds);
                string ips = string.Join(",", ids);
                if (!string.IsNullOrEmpty(ips))
                {if(machineRoomId!=0)
                    return db.Database.SqlQuery<IP>("select * from IPs where Id not in (" + ips + ") and MachineRoomId=" + machineRoomId + " and isDelete IS NULL").ToList();
                else
                        return db.Database.SqlQuery<IP>("select * from IPs where Id not in (" + ips + ") and isDelete IS NULL").ToList();
                }
                else
                    return db.IPs.Where(o => o.MachineRoomId == machineRoomId && !o.isDelete.HasValue).ToList();
            }
        }
        public static List<string> List(string ids)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                List<string> Ips = new List<string>();
                if (string.IsNullOrEmpty(ids))
                    return Ips;
                List<string> ipIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList();
                foreach (string s in ipIds)
                {
                    int id = Int32.Parse(s);
                    Ips.Add(Get(id).Ip);
                }
                return Ips;
            }
        }
        public static void IPCount(out int count, out int useCount, out int subCount)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                count = db.IPs.Where(o=>!o.isDelete.HasValue).Count();
                IQueryable<PutawayServer> p = db.PutawayServers.Where(o => o.Statu == 1);
                List<int> ids = p.Select(o => o.IPId.Value).ToList();
                List<string> arrIds = p.Where(o => !string.IsNullOrEmpty(o.SubIPIds)).Select(o => o.SubIPIds).ToList();
                string str = String.Join(",", arrIds);
               
                useCount = ids.Count() + str.Split(new char[] { ','},StringSplitOptions.RemoveEmptyEntries).Count();
                subCount = count - useCount;
            }
        }
        public static string GetSubIp(string ids)
        {
            using (ZichanDBContext db = new ZichanDBContext())
            {
                if (!string.IsNullOrEmpty(ids))
                {
                    List<string> ips = db.Database.SqlQuery<IP>("select * from IPs where Id in(" + ids + ")").Select(o => o.Ip).ToList();
                    return string.Join(",", ips);
                }
                else
                    return string.Empty;
            }
        }
    }
}
